﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using IPC.LogCommon.DelegateAndEvent;
using IPC.LogCommon.log4net;
using IPC.WinForm.ViewModel;
using LiveChartsCore.SkiaSharpView;
using static System.Net.WebRequestMethods;

namespace IPC.WinForm.BaseForm
{
    public partial class FrmSerial : Form
    {
        private ViewModel.ViewModel _viewModel;
        public FrmSerial(ViewModel.ViewModel viewModel)
        {
            InitializeComponent();
            InitForm(viewModel);
            DelegateAndEvent.Instance.RefreshSeriesEvent += AddItem;
        }

        private void InitForm(ViewModel.ViewModel viewModel)
        {
            _viewModel = viewModel;
            this.cartesianChart1.Series = _viewModel.Series;
            this.cartesianChart1.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top | AnchorStyles.Bottom;
            this.cartesianChart1.LegendPosition = LiveChartsCore.Measure.LegendPosition.Right;
            this.cartesianChart1.ZoomMode = LiveChartsCore.Measure.ZoomAndPanMode.X;
            this.cartesianChart1.XAxes = new Axis[]
            {
                new DateTimeAxis(TimeSpan.FromSeconds(1),date=>date.ToString())
            };
            //this.cartesianChart1.LegendTextSize = 3;
        }

        private delegate void AddItemDelegate(string fullName, string recordTime, string value);
        private void AddItem(string fullName,string recordTime,string value)
        {
            try
            {
                if (this.cartesianChart1.InvokeRequired)
                {
                    AddItemDelegate addItemDelegate = new AddItemDelegate(AddItem);
                    this.cartesianChart1.BeginInvoke(addItemDelegate,new object[] { fullName, recordTime, value });
                }
                else
                {
                    _viewModel.AddItem(fullName, recordTime, value);
                }
            }
            catch (Exception ex)
            {
                LogClass.Instance.Error($"添加点位错误{ex.Message}");
            }
        }
    }
}
